using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Core;

namespace DaoGenerator
{
	public class FilterFillFileGenerator
	{
		private const string DAO_SUPPORT_DIRECTORY = @"GeneratedFiles\Model\Dao\Support\";

		private const string FILTER_EXTENSIONS_CLASS_WRAPPER = 
@"using Triton.Controller.Request;
using {SUPPORT_NAMESPACE};
using Triton.Model.Dao;
using Triton.Model.Dao.Support;
using Triton.Utilities;

namespace {NAMESPACE}
{
	public static class FilterExtensions
	{
{METHODS}
	}
}";

		public FilterFillFileGenerator() {}


		public FilterFillFileGenerator(Assembly assembly)
		{
			this.Assembly = assembly;
		}


		public Assembly Assembly { get; set; }


		public void Execute(IEnumerable<string> selectedClassNames)
		{
			//read in the template
			TextReader reader =
				new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\TemplateFiles\FilterFillFile.template");

			string template = reader.ReadToEnd();

			string methods = "";

			string nameSpace = "";

			string supportNamespace = "";

			foreach (string fullName in selectedClassNames) {
				//create a new template string
				string singleMethod = template;

				Type classType = this.Assembly.GetType(fullName);
				string className = classType.Name;

				nameSpace = Utilities.GetDaoSupportNameSpace(classType.Namespace);
				supportNamespace = Utilities.GetSupportRequestNameSpace(classType.Namespace);
				
				MemberInfo idMemberInfo = classType.GetMember("Id")[0];
				string idType = Utilities.GetRealTypeFromMemberProperty(idMemberInfo).Name;

				idType = Utilities.GetCommonNameForType(idType);

				singleMethod = singleMethod.Replace("{ID_TYPE}", Utilities.Capitalize(idType));
				singleMethod = singleMethod.Replace("{CLASS_NAME}", className);

				methods += singleMethod + Environment.NewLine + Environment.NewLine;
			}

			string classFile = FILTER_EXTENSIONS_CLASS_WRAPPER.Replace("{METHODS}", methods);

			classFile = classFile.Replace("{NAMESPACE}", nameSpace);
			classFile = classFile.Replace("{SUPPORT_NAMESPACE}", supportNamespace);

			Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + DAO_SUPPORT_DIRECTORY);

			TextWriter writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + DAO_SUPPORT_DIRECTORY + "FilterExtensions.cs");

			writer.Write(classFile);

			writer.Flush();
			writer.Close();
		}


	
	}
}